package org.outlook.common.invoke;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class DynamicInvoke {

	/**
	 * 
	 * @param contxtPath
	 * @param parameterTypes
	 * @param parameterValues
	 * @param returnType
	 * @return
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	@SuppressWarnings("unchecked")
	public static Object dynamicInvoke(String contxtPath,
			List<Object> parameterTypes, List<Object> parameterValues,
			Class returnType) {
		if (StringUtils.isBlank(contxtPath))
			return null;
		if (!contxtPath.contains("."))
			return null;
		if (parameterTypes.size() != parameterValues.size())
			return null;
		String className = contxtPath.substring(0, contxtPath.lastIndexOf("."));
		String methodName = contxtPath
				.substring(contxtPath.lastIndexOf(".") + 1);

		try {
			Class clazz = Class.forName(className);
			Object object = clazz.newInstance();
			Class[] paramTypes = new Class[parameterTypes.size()];
			Object[] paramValues = new Object[parameterValues.size()];
			int index = 0;
			for (Object o : parameterTypes) {
				paramTypes[index] = (Class) o;
				paramValues[index] = parameterValues.get(index);
				index++;
			}
			Method method = clazz.getMethod(methodName, paramTypes);
			if (null != method) {
				Object result = method.invoke(object, paramValues);
				// if(null != returnType)
				// return ((Class)returnType) result;
				return result;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
